package com.iretailer.report.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iretailer.report.mapper.UserMallMapper;
import com.iretailer.report.model.UserMall;
import com.iretailer.report.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * @Auther: xjw
 * @Date: 2019/2/23 22:46
 * @Description:
 */
@Service
public class UserMallService extends ServiceImpl<UserMallMapper, UserMall> {

    @Autowired
    private UserMallMapper userMallMapper;
    @Autowired
    private UserService userService;

    @Transactional(propagation = Propagation.REQUIRED)
    public boolean insertUsersMalls(String userId, List<String> mallIds) {
        if (StringUtil.notEmpty(userId) && mallIds != null) {
            // 删除不是创建的
            userMallMapper.delete(new QueryWrapper<UserMall>().lambda().eq(UserMall::getUserId, userId).ne(UserMall::getCreated, 1));
            // 此处不能删除所有的
            userMallMapper.insertUsersMalls(userId, mallIds);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 用户查询 user 下拥有的 mall
     *
     * @param userId
     * @return
     */
    public List<String> selectUserMallIds(String userId) {
        List<String> childens = userService.getTreeId(userId);
        childens.add(userId);
        List<String> mallIds = selectMallIdsByUserIds(childens);
        if (mallIds.size() == 0) {
            mallIds.add("1");
        }
        return mallIds;
    }

    public List<String> selectMallIdsByUserIds(List<String> userIds) {
        return userMallMapper.selectMallIdsByUserIds(userIds);
    }

    public List<Map<String,Object>> selectMallsByUserIds(List<String> userIds) {
        return userMallMapper.selectMallsByUserIds(userIds);
    }

    public List<Map<String, Object>> selectAllMalls() {
        return userMallMapper.selectAllMalls();
    }
}
